package com.teemo.equipment.controller;

import cn.hutool.core.io.FileUtil;
import com.teemo.equipment.domain.vo.ResultVO;
import com.teemo.equipment.exception.BizException;
import com.teemo.equipment.service.FileUploadService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author Teemo
 */
@RequestMapping("/file")
@RestController

public class FileController {

    @Resource
    private FileUploadService fileUploadService;

    @PostMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultVO<Long> upload(@RequestPart MultipartFile file) {
        Long fileId = fileUploadService.upload(file);
        return ResultVO.success(fileId);
    }

    @GetMapping(value = "/download/{fileId}")
    public void download(@PathVariable Long fileId, HttpServletResponse response) {
        fileUploadService.download(fileId,response);
    }

    // 1.直接返回一个url，url可以通过下载接口进行组装
    // 2. nginx 配置静态资源，直接返回静态资源

    @PostMapping(value = "/upload1",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultVO<String> upload1(@RequestPart MultipartFile file) {
        Long fileId = fileUploadService.upload(file);
        String url="http://localhost:9001/download/"+fileId;
        return ResultVO.success(url);
    }

    @PostMapping(value = "/upload2",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultVO<String> upload2(@RequestPart MultipartFile file) {
        String nginxDir ="D:\\ProgramFiles\\nginx-1.26.1\\html\\files\\";
        String originalFilename = file.getOriginalFilename();
        String mainName = FileUtil.mainName(originalFilename);
        String extName = FileUtil.extName(originalFilename);
        String fileName = mainName + "_" + UUID.randomUUID() + "." + extName;

        String absolutePath = nginxDir + fileName;

        try {
            FileUtil.writeBytes(file.getBytes(), absolutePath);
        } catch (IOException e) {
            throw BizException.of("文件上传失败");
        }

        String url="http://localhost:80/files/"+fileName;
        return ResultVO.success(url);
    }

}
